package com.lumeng.spring.common.utils;

import com.lumeng.spring.common.constant.Constants;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.security.Key;

import static com.lumeng.spring.common.utils.Arguments.notEmpty;

/**
 * @Author: _刘莉莉
 * @Description:
 * @Date: Created in 20:00 2019/12/5
 * @Modified By:
 */
@Slf4j
@Component
public class TokenManager {

    // token的过期时间
    public static final long TOKEN_EXPIRED = Constants.TIMESTAMP_WEEK;
    // token的key
    public static final String REDIS_KEY_AUTH_TOKEN_PREFIX = "token:";

    // 秘钥
    private static final Key KEY = new SecretKeySpec("Etc888".getBytes(), SignatureAlgorithm.HS256.getJcaName());

    @Autowired
    private RedisDao redisDao;


    /**
     * 删除token
     *
     * @param token : token
     */
    public void deleteToken(String token) {
        redisDao.del(REDIS_KEY_AUTH_TOKEN_PREFIX + token);
    }


    /**
     * 从当前请求中获取token信息
     */
    public String getTokenFormRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader(Constants.HTTP_HEAD_AUTHORIZATION);
        log.info("【TokenManager】getTokenFormRequest token={}", token);
        notEmpty(token, "Authorization cannot be empty");
        return token;
    }


    /**
     * 将token和用户id缓存到redis中, 缓存时间是一周
     *
     * @param token  : token
     * @param userId : 用户id
     */
    public void cacheToken(String token, Integer userId) {
        redisDao.set(REDIS_KEY_AUTH_TOKEN_PREFIX + token, userId, TOKEN_EXPIRED);
    }


    /**
     * 从redis中获取用户信息
     *
     * @param token : token
     */
    public String getUserIdFromCache(String token) {
        //3代表微信小程序端 暂时写死
        String memberNo = (String) redisDao.get(REDIS_KEY_AUTH_TOKEN_PREFIX + ":" + 3 + token );
        log.info("【TokenManager】getUserIdFromCache memberNo={}", memberNo);
        return memberNo;
    }



}
